#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "Dialog_addCandidates.h"

MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
	ui(new Ui::MainWindow)
{
	ui->setupUi(this);
	sl.createDataFile(DBName);
	sl.openDataBase(DBName);
	if (!sl.isExistTable(medicineRecord) && !sl.isExistTable(medicineList))
		dp.createTable();
	group = settings.value("group", "today").toString();
	detial = settings.value("detial", false).toBool();
	initInterface();
	if (!settings.contains("group")) {
		QMessageBox box(QMessageBox::Information,"Welcome",tr("<p><img src=':/resource/th.jpg'>      名字不是我取的</img></p>"));
		box.setStandardButtons (QMessageBox::Ok);
		box.setButtonText (QMessageBox::Ok,QString("好好，我知道了..."));
		box.exec ();
	}
	backupDB();
}

MainWindow::~MainWindow()
{
	sl.closeDataBase();
	if (system_tray != NULL)
		system_tray->hide();
	settings.setValue("group", group);
	settings.setValue("detial", detial);
	delete ui;
}


void MainWindow::refreshComboboxList()
{
	if (sl.openDataBase(DBName)) {
		QStringList names = dp.getMedicineListsNames();
		ui->comboBox_name->clear();
		ui->comboBox_name->addItems(names);
		ui->comboBox_name->setCurrentText("");
		ui->spinBox_num->setValue(1);
	}
	else {
		qDebug()<<"open database failed!";
	}
}

void MainWindow::refreshRecordTable()
{
	ui->tableWidget_prescriptionList->setRowCount(0);
	ui->tableWidget_prescriptionList->clearContents();
	if (sl.openDataBase(DBName)) {
		records = dp.getMedicineRecordsByGroup(group, detial);
		for (int i=0; i<records.length(); i++) {
			ui->tableWidget_prescriptionList->insertRow(i);
			QTableWidgetItem* itemName = new QTableWidgetItem(records.at(i).name);
			itemName->setData(Qt::UserRole, records.at(i).id);
			ui->tableWidget_prescriptionList->setItem(i, 0, itemName);
			itemName->setToolTip(records.at(i).name);

			QTableWidgetItem* itemSum = new QTableWidgetItem(QString::number(records.at(i).sum)+" ("+records.at(i).unit+")");
			ui->tableWidget_prescriptionList->setItem(i, 1, itemSum);
			itemSum->setToolTip((QString::number(records.at(i).sum)));

			QTableWidgetItem* itemDate = new QTableWidgetItem(records.at(i).date.toString("yyyy年MM月dd日"));
			ui->tableWidget_prescriptionList->setItem(i, 2, itemDate);
			itemDate->setToolTip((records.at(i).date.toString()));
		}
	}
	else {
		qDebug()<<"open database failed!";
	}


	ui->tableWidget_prescriptionList->setColumnWidth(0, 550);
	ui->tableWidget_prescriptionList->setColumnWidth(1, 60);

//	ui->tableWidget_prescriptionList->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch);

//	ui->tableWidget_prescriptionList->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents);
}

void MainWindow::refreshRecordTable(QString group)
{
	ui->tableWidget_prescriptionList->setRowCount(0);
	ui->tableWidget_prescriptionList->clearContents();
	if (sl.openDataBase(DBName)) {
		records = dp.getMedicineRecordsByGroup(group, ui->checkBox_deital->isChecked());
		for (int i=0; i<records.length(); i++) {
			ui->tableWidget_prescriptionList->insertRow(i);
			QTableWidgetItem* itemName = new QTableWidgetItem(records.at(i).name);
			itemName->setData(Qt::UserRole, records.at(i).id);
			ui->tableWidget_prescriptionList->setItem(i, 0, itemName);
			itemName->setToolTip(records.at(i).name);

			QTableWidgetItem* itemSum = new QTableWidgetItem(QString::number(records.at(i).sum)+" ("+records.at(i).unit+")");
			ui->tableWidget_prescriptionList->setItem(i, 1, itemSum);
			itemSum->setToolTip((QString::number(records.at(i).sum)));

			QTableWidgetItem* itemDate = new QTableWidgetItem(records.at(i).date.toString("yyyy年MM月dd日"));
			ui->tableWidget_prescriptionList->setItem(i, 2, itemDate);
			itemDate->setToolTip((records.at(i).date.toString()));
		}
	}
	else {
		qDebug()<<"open database failed!";
	}
}

void MainWindow::initSystemTray()
{
	system_tray = new QSystemTrayIcon();

	//放在托盘提示信息、托盘图标

	system_tray ->setToolTip(QString("我就是托盘"));
	system_tray ->setIcon(QIcon(":/resource/Medicine_128px_1188479_easyicon.net.ico"));


	QList<QAction*> actions;
	QAction* act_exit = new QAction("退出");
	connect(act_exit, SIGNAL(triggered(bool)), qApp, SLOT(quit()));
	actions.append(act_exit);
	trayMenu.addActions(actions);
	system_tray->setContextMenu(&trayMenu);

	//点击托盘执行的事件
	connect(system_tray , SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(showNormal()));

	//connect(tray_menu, SIGNAL(showWidget()), this, SLOT(showNormal()));

	//显示托盘
	system_tray->show();
	system_tray->showMessage(QString("软件"), QString("启动成功"));
}

void MainWindow::initInterface()
{
	refreshComboboxList();
	refreshRecordTable();

	ui->dateEdit_today->setDate(QDate::currentDate());
	QList<QAction*> actions;

	QAction* act0 = new QAction(QIcon(":/resource/delete.ico"), "删除最近的记录");
	connect(act0, SIGNAL(triggered(bool)), this, SLOT(delete_record()));
	actions.append(act0);
	menu.addActions(actions);

	if (group == "today")
		ui->pushButton_lookUpToday->setChecked(true);
	else if (group == "month")
		ui->pushButton_lookUpThisMonth->setChecked(true);
	else if (group == "year")
		ui->pushButton_lookUpThisYear->setChecked(true);

	ui->checkBox_deital->setChecked(detial);
	initSystemTray();
}

bool MainWindow::initUniqueInstance()
{
	QString serverName = QCoreApplication::applicationName();
	QLocalSocket socket;
	socket.connectToServer(serverName);
	if (socket.waitForConnected(500)) { //如果能够连接得上的话，将参数发送到服务器，然后退出
		QTextStream stream(&socket);
		QStringList args = QCoreApplication::arguments();
		if (args.count() > 1)
			stream << args.last();
		else
			stream << QString();
		stream.flush();
		socket.waitForBytesWritten();
		QTimer::singleShot(0, qApp, SLOT(quit()));
		return false;
	}
	//运行到这里，说明没有实例在运行，那么创建服务器。
	m_localServer = new QLocalServer(this);
	connect(m_localServer, SIGNAL(newConnection()), this, SLOT(newLocalSocketConnection())); //监听新到来的连接
	if (!m_localServer->listen(serverName)) {
		if (m_localServer->serverError() == QAbstractSocket::AddressInUseError
			&& QFile::exists(m_localServer->serverName())) { //确保能够监听成功
			QFile::remove(m_localServer->serverName());
			m_localServer->listen(serverName);
		}
	}
	return true;
}

void MainWindow::backupDB()
{
	if (QDate::currentDate().day()==1) {
		QString backupName = QString(DBName)+"."+QDate::currentDate().toString("yyyy-MM-dd");
		QFile file(backupName);
		if (!file.exists()){
			if (!QFile::copy(DBName, backupName)) {
				QMessageBox::warning(this, "数据备份失败", "数据备份失败");
			}
		}
	}
}

void MainWindow::newLocalSocketConnection()
{
	QLocalSocket *socket = m_localServer->nextPendingConnection();
	if (!socket)
		return;
	socket->waitForReadyRead(1000);
	QTextStream stream(socket);
	;
	delete socket;
	this->showNormal();
	this->activateWindow(); //记得激活窗口哦
}
///
/// \brief MainWindow::closeEvent
/// \param event
///重载事件接受函数
void MainWindow::closeEvent(QCloseEvent *event)
{
	if(system_tray->isVisible())
	{
		hide(); //隐藏窗口
		event->ignore(); //忽略事件
	}
}

///
/// \brief MainWindow::on_pushButton_test_clicked
///test
void MainWindow::on_pushButton_test_clicked()
{
	sl.createDataFile(DBName);
	sl.openDataBase(DBName);
	dp.createTable();
	dp.addMedicineRecord("wangzhi", 2, "g", QDate::currentDate());
	sl.closeDataBase();
}

///
/// \brief MainWindow::on_pushButton_addNew_clicked
/// 添加新的记录
void MainWindow::on_pushButton_addNew_clicked()
{
	sl.createDataFile(DBName);
	sl.openDataBase(DBName);

	dp.createTable();
	QString name = ui->comboBox_name->currentText();
	if (name.length() == 0){
		QMessageBox::critical(this, "添加失败", "未输入药名");
		return;
	}
	int sum		 = ui->spinBox_num->value();
	QString unit = ui->comboBox_unit->currentText();
	if (unit.length() == 0){
		QMessageBox::critical(this, "添加失败", "未输入单位");
		return;
	}
	QDate date   = ui->dateEdit_today->date();
	dp.addMedicineRecord(name, sum, unit, date);
	if (ui->pushButton_lookUpThisMonth->isChecked())
		refreshRecordTable("month");
	else if (ui->pushButton_lookUpThisYear->isChecked())
		refreshRecordTable("year");
	else
		refreshRecordTable();
}

////
/// \brief MainWindow::delete_record
///删除
void MainWindow::delete_record()
{
	int id = ui->tableWidget_prescriptionList->item(ui->tableWidget_prescriptionList->currentRow(), 0)->data(Qt::UserRole).toInt();
	QString name = ui->tableWidget_prescriptionList->item(ui->tableWidget_prescriptionList->currentRow(),0)->text();
	if (QMessageBox::question(this, "删除", "确定删除 "+name+" ?", QMessageBox::Yes|QMessageBox::No) == QMessageBox::Yes) {
		if (dp.removeMedicineRecord(id)){
			refreshRecordTable();
			//ui->tableWidget_prescriptionList->removeRow(ui->tableWidget_prescriptionList->currentRow());
		}
		else {
			QMessageBox::critical(this, "删除", "删除失败!");
		}
	}
}
///
/// \brief MainWindow::on_actionaddOptions_triggered
/// 添加新的默认选项
void MainWindow::on_actionaddOptions_triggered()
{
	Dialog_addCandidates da;
	da.exec();
	refreshComboboxList();
}

///
/// \brief MainWindow::on_tableWidget_prescriptionList_customContextMenuRequested
/// \param pos
///	右键列表
void MainWindow::on_tableWidget_prescriptionList_customContextMenuRequested(const QPoint &pos)
{
	menu.exec(QCursor::pos());
}

void MainWindow::on_actioncontactMe_triggered()
{
	QMessageBox::information(this, "关于","联系方式 e-mail:whiteLine47@163.com 欢迎反馈问题   .\n"
										 "数据保存在"+QDir::currentPath()+"/"+DBName+" 文件中，删除之后数据将会丢失！\n"
										 "更新说明:\n"
										 "    2018/2/5:增加数据库备份功能（每月1号数据库会备份一次，防止数据丢失）");
}

///
/// \brief MainWindow::on_comboBox_name_currentTextChanged
/// \param arg1
///输入了新的药名
void MainWindow::on_comboBox_name_currentTextChanged(const QString &arg1)
{
	QStringList units = dp.getUnitByName(arg1);
	ui->comboBox_unit->clear();
	ui->comboBox_unit->addItems(units);
	ui->comboBox_unit->setCurrentIndex(0);
	int default_sum = dp.getDefaultSumByName(arg1);
	ui->spinBox_num->setValue(default_sum);
}

///
/// \brief MainWindow::on_pushButton_lookUpToday_clicked
/// 查看今天， 本月， 本年的数据
void MainWindow::on_pushButton_lookUpToday_clicked()
{
	group = "today";
	refreshRecordTable(group);
}

void MainWindow::on_pushButton_lookUpThisMonth_clicked()
{
	group = "month";
	refreshRecordTable(group);
}

void MainWindow::on_pushButton_lookUpThisYear_clicked()
{
	group = "year";
	refreshRecordTable(group);
}

void MainWindow::on_pushButton_lookUpAll_clicked()
{
	group = "all";
	refreshRecordTable();
}

///
/// \brief MainWindow::on_checkBox_deital_stateChanged
/// \param arg1
///显示细节
void MainWindow::on_checkBox_deital_stateChanged(int arg1)
{
	arg1 = arg1;
	if (ui->pushButton_lookUpToday->isChecked()) {
		group = "today";
	}
	else if (ui->pushButton_lookUpThisMonth->isChecked()) {
		group = "month";
	}
	else if (ui->pushButton_lookUpThisYear->isChecked()) {
		group = "year";
	}
	else {
		group = "all";
	}
	detial = ui->checkBox_deital->isChecked();
	refreshRecordTable(group);
}

///
/// \brief MainWindow::on_pushButton_advance_clicked
///查看图形
void MainWindow::on_pushButton_advance_clicked()
{
	Form_advancedStatistics* dm = new Form_advancedStatistics(NULL, group, detial);
	dm->show();
}

///
/// \brief MainWindow::on_actionexportCSV_triggered
///导出功能
void MainWindow::on_actionexportCSV_triggered()
{
	QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
								 QDir::homePath()+"/"+QDateTime::currentDateTime().toString("yyyy-MM-dd HH_mm_ss")+".csv",
								 tr("CSV (*.csv)"));
	QFile file(fileName);
	if (file.open(QFile::ReadWrite)) {
		QString content;
		if (group=="today")
			content = "今天("+QDate::currentDate().toString("yyyy-MM-dd")+"),,";
		else if (group == "month")
			content = "这个月("+QDate::currentDate().toString("yyyy-MM")+"),,";
		else if (group == "year")
			content = "今年("+QDate::currentDate().toString("yyyy")+"),,";
		else content = "所有(截止到目前:"+QDate::currentDate().toString("yyyy-MM-dd")+"),,";

		file.write(content.toUtf8());
		file.write("\n");
		file.write("名称,数量,最近添加\n");
		records = dp.getMedicineRecordsByGroup(group, ui->checkBox_deital->isChecked());
		for (int i=0; i<records.length(); i++) {
			content = records.at(i).name+",";
			file.write(content.toUtf8());
			content = QString::number(records.at(i).sum)+" ("+records.at(i).unit+"),";
			file.write(content.toUtf8());
			content = records.at(i).date.toString("yyyy年MM月dd日");
			file.write(content.toUtf8());
			file.write("\n");
		}
		file.close();
		QMessageBox::information(this, "导出文件", "保存文件成功！");
	}
	else {
		QMessageBox::critical(this, "导出文件失败", file.errorString());
	}
}
